package future;


import java.util.concurrent.*;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

class JannaFutureTask<T> implements Runnable {

    private Callable<T> callable;
    private volatile T result;
    private Sync sync = new Sync();

    public JannaFutureTask(Callable<T> callable) {
        this.callable = callable;
    }

    public T get() {
        // 获取共享锁
        sync.acquireShared(1);
        return result;
    }

    @Override
    public void run() {
        try {
            result = callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sync.releaseShared(1);
        }
    }

    private class Sync extends AbstractQueuedSynchronizer {
        public Sync() {
            setState(1);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            return getState() == 0 ? 1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            setState(0);
            return true;
        }
    }
}

public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<String> callable = () -> {
            Thread.sleep(1000);
            return "Hello World!";
        };

//        ExecutorService executorService = Executors.newCachedThreadPool();
//        Future<String> future = executorService.submit(callable);
//        executorService.shutdown();

        JannaFutureTask<String> future = new JannaFutureTask<>(callable);
        new Thread(future).start();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println("ready to get");
                System.out.println(future.get());
            }).start();
        }
        System.out.println("ready to get");
        System.out.println(future.get());
    }
}
